/**
 * @author Mie Plougstrup, Anders Abildgaard, Bo Stokholm 
 * @Version 16-12-2014
 */

package ctrLayer;

import java.sql.Connection;
import java.util.ArrayList;

import modelLayer.Address;
import modelLayer.Driver;
import modelLayer.Supplier;
import dbLayer.DbConnection;
import dbLayer.DbDriver;
import dbLayer.DbMaxId;
/**
 * @author Bo Nielsen
 * */
public class CtrDriver {
	private CtrBusinessPartner ctrBusinessPartner;
	private CtrAddress ctrAddress;
	private DbDriver dbDri;
	private DbConnection con;

	public CtrDriver(){
		con = DbConnection.getInstance();
		dbDri = new DbDriver();
		ctrAddress = new CtrAddress();
		ctrBusinessPartner = new CtrBusinessPartner();
	}

	/**
	 * Find a driver by driver id.
	 * @param Driver driver
	 * @return Driver
	 */
	public Driver retrieveDriver(int driverId){
		return dbDri.retrieveById(driverId);
	}
	
	public Driver retrieveDriverByPhone(String phoneNo) {
		return dbDri.retrieveByPhone(phoneNo);
	}
	
	/**
	 * Returns a full list of all the drivers.
	 * @return ArrayList<Driver> list
	 */
	public ArrayList<Driver> retrieveAllDrivers(){
		return dbDri.retrieveAllDrivers();
	}

	public ArrayList<Driver> retrieveUnusedDrivers(int dispListId) {
		return dbDri.retrieveUnusedDrivers(dispListId);
	}

	/**
	 * Returns a driver by drivers first name.
	 * @param String firstname
	 * @return Driver
	 */
	public Driver retrieveDriverByFName(String fname){
		return dbDri.retrieveByFName(fname);
	}
	/**
	 * Updates a driver in the database.
	 * @param Driver driver
	 */
	public void update(Driver d){
		dbDri.update(d);
	}
	/**
	 * Insert a driver into the database.
	 * @param Driver driver
	 */
	public void createWSup(String fName, String lName, String phoneNo, Supplier supplier) throws Exception{
		int id = DbMaxId.getMaxID("driverId", "driver") + 1;
		Driver d = new Driver(id, fName, lName, phoneNo, supplier);
		dbDri.insert(d);
	}
	/**
	 * Delete a driver from the database.
	 * @param Driver driver
	 */
	public void delete(Driver d){
		dbDri.delete(d);
	}

	public void createWOSup(String fName, String lName, String driPhone, String supName, String street, String houseNo,
			String postalCode, String city, String supPhone) throws Exception {
		int driId = DbMaxId.getMaxID("driverId", "driver") + 1;
		//int supId = DbMaxId.getMaxID("partnerId", "businessPartner");
		try{
		con.startTransaction();
		String country = ctrAddress.retrieveCountryByCode(postalCode);
		Address address = ctrAddress.create("", street, houseNo, postalCode, city, country, 1);
		Supplier supplier = ctrBusinessPartner.createSupplier(supName, supPhone, address);
		Driver d = new Driver(driId, fName, lName, driPhone, supplier);
		dbDri.insert(d);
		con.commitTransaction();
		} catch(Exception e) {
			con.rollbackTransaction();
			throw e;
		}
	}

}
